﻿using System;
using System.ServiceProcess;

namespace VentHost.Lib
{
    public class Service : IDisposable
    {
        private const string ServiceName = "Ventrilo";
        private ServiceController sc;

        public bool IsRunning()
        {
            bool ret = false;

            try
            {
                sc = new ServiceController(ServiceName);

                if (sc.Status == ServiceControllerStatus.Running)
                {
                    ret = true;
                }
                else
                {
                    ret = false;
                }
            }
            catch (Exception)
            {
                ret = false;
                //throw;
            }

            return ret;
        }

        public bool Start()
        {
            bool ret = false;

            try
            {
                sc = new ServiceController(ServiceName);
                
                if (sc.Status == ServiceControllerStatus.Stopped)
                {
                    sc.Start();
                    ret = IsRunning();
                }
            }
            catch (Exception)
            {
                ret = false;
                throw;
            }
    
            return ret;
        }

        public bool Stop()
        {
            bool ret = false;

            try
            {
                ServiceController sc = new ServiceController(ServiceName);

                if (sc.Status != ServiceControllerStatus.Stopped)
                {
                    sc.Stop();
                    if (IsRunning()) { ret = false; } else { ret = true; }
                }
            }
            catch (Exception)
            {
                ret = false;
                throw;
            }

            return ret;
        }

        public void Dispose()
        {
            try
            {
                sc.Dispose();
            }
            catch (Exception)
            {                
                //throw;
            }
        }
    }
}